package com.guomei.controller.curse;

import com.guomei.bean.curse.ByUserIdGetAllDTO;
import com.guomei.bean.curse.CreateOrUpdateUserCourseLearnDTO;
import com.guomei.bean.curse.UserCourseLearn;
import com.guomei.bean.curse.vo.CourseLearnStatDto;
import com.guomei.service.curse.UserCourseLearnService;
import com.guomei.utils.JwtUtil;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户课程学习记录Controller
 */
@RestController
@RequestMapping("/api1/userCourseLearn")
@Slf4j
public class UserCourseLearnController {
    @Resource
    private UserCourseLearnService userCourseLearnService;

    /**
     * 根据条件查询学习计划
     */
    @PostMapping("/listByCondition")
    public Result<?> listByCondition(@RequestBody UserCourseLearn userCourseLearn) {
        log.info("根据条件查询学习计划入参->{}", userCourseLearn);
        if (userCourseLearn == null || userCourseLearn.getPageNum() == null || userCourseLearn.getPageSize() == null){
            return Result.fail("分页字段信息缺失，查询失败");
        }
        // 验证分页参数是否有效
        if (userCourseLearn.getPageNum() <= 0 || userCourseLearn.getPageSize() <= 0) {
            return Result.fail("分页参数无效");
        }
        try {
            return userCourseLearnService.listByCondition(userCourseLearn);
        } catch (Exception e) {
            log.info("根据条件查询学习计划异常->{}", e);
            return Result.error("根据条件查询学习计划异常");
        }
    }


    @PostMapping("/listByIds")
    public Result<?> listByIds(@RequestBody List<Long> ids, HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        log.info("Authorization Header: {}", authHeader);
        
        String token = null;
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            token = authHeader.substring(7);
            log.info("提取的Token: {}", token);
        } else {
            log.warn("Authorization头格式不正确或为空: {}", authHeader);
        }
        
        Long userIdFromToken = null;
        if (token != null) {
            userIdFromToken = JwtUtil.getUserIdFromToken(token);
        }
        
        log.info("解析得到的用户ID: {}", userIdFromToken);
        log.info("根据id列表查询学习记录入参->{}", ids);
        return userCourseLearnService.listByVideoIdsAndUserId(ids, userIdFromToken);
    }

    /**
     * 根据用户id查询全部学习记录信息
     */
    @PostMapping("/byUserIdGetAll")
    public Result<?> byUserIdGetAll(@RequestBody ByUserIdGetAllDTO byUserIdGetAllDTO) {
        log.info("根据用户id查询全部学习记录信息入参->{}", byUserIdGetAllDTO);
        try {
            if (byUserIdGetAllDTO == null || byUserIdGetAllDTO.getPageNum() == null || byUserIdGetAllDTO.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (byUserIdGetAllDTO.getPageNum() <= 0 || byUserIdGetAllDTO.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return userCourseLearnService.byUserIdGetAll(byUserIdGetAllDTO);
        } catch (Exception e) {
            log.info("根据用户id查询全部学习记录信息异常->{}", e);
            return Result.error("根据用户id查询全部学习记录信息异常");
        }
    }

    /**
     * 保存/更新学习记录
     */
    @PostMapping("/save")
    public Result<?> save(@Valid @RequestBody CreateOrUpdateUserCourseLearnDTO createOrUpdateUserCourseLearnDTO, BindingResult result) {
        log.info("保存/更新学习记录入参->{}", createOrUpdateUserCourseLearnDTO);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            UserCourseLearn userCourseLearn = new UserCourseLearn();
            userCourseLearn.setUserId(createOrUpdateUserCourseLearnDTO.getUserId());
            userCourseLearn.setCourseId(createOrUpdateUserCourseLearnDTO.getCourseId());
            userCourseLearn.setVideoId(createOrUpdateUserCourseLearnDTO.getVideoId());
            userCourseLearn.setLearnDuration(createOrUpdateUserCourseLearnDTO.getLearnDuration());
            userCourseLearn.setProgress(createOrUpdateUserCourseLearnDTO.getProgress());
            userCourseLearn.setStatus(createOrUpdateUserCourseLearnDTO.getStatus());
            userCourseLearn.setLastLearnTime(createOrUpdateUserCourseLearnDTO.getLastLearnTime());
            userCourseLearn.setCreatedTime(createOrUpdateUserCourseLearnDTO.getCreatedTime());
            userCourseLearn.setUpdatedTime(createOrUpdateUserCourseLearnDTO.getUpdatedTime());
            boolean save = userCourseLearnService.save(userCourseLearn);


            
            return save ? Result.success() : Result.fail("保存失败");
        } catch (Exception e) {
            log.info("保存/更新学习记录处理失败", e);
            return Result.error("保存/更新学习记录处理失败");
        }
    }


    @PostMapping("/getCourseLearnStats")
    public Result<?> getCourseLearnStats(@RequestBody CourseLearnStatDto courseLearnStatDto) {
        log.info("根据用户ID查询学习记录入参->{}", courseLearnStatDto);
        return userCourseLearnService.getVideoLearnStats(courseLearnStatDto);
    }
}
